﻿using BizModels;
using DataModel;
using IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repositories
{
    public class MemberProfileRepository : RepositoryBase, IMemberProfileRepository
    {
        public MemberProfileRepository()
        {
            Context = new HinokyEntities();
        }

        public int SaveMemberProfile(MemberProfileT requestData)
        {
            var data = Context.MemberProfile.FirstOrDefault(s => s.UserKey == requestData.UserKey);

            // 수정
            if (data != null)
            {
                data.NickName = requestData.NickName;
                if (!string.IsNullOrEmpty(requestData.ProfileImagePath))
                {
                    data.ProfileImageUrl = requestData.ProfileImageUrl;
                    data.ProfileImagePath = requestData.ProfileImagePath;
                }
                data.UpdateDate = DateTime.Now;
                data.UpdateUserKey = requestData.UpdateUserKey;
            }
            // 등록
            else
            {
                var profile = new MemberProfile();
                profile.UserKey = requestData.UserKey;
                profile.NickName = requestData.NickName;

                profile.ProfileImageUrl = requestData.ProfileImageUrl;
                profile.ProfileImagePath = requestData.ProfileImagePath;
                
                profile.InsertDate = DateTime.Now;
                profile.InsertUserKey = requestData.InsertUserKey;

                Context.MemberProfile.Add(profile);
            }

            Context.SaveChanges();

            return 1;
        }

        public MemberProfileT GetMemberProfile(int userKey)
        {
            try
            {
                var data = Context.MemberProfile.FirstOrDefault(s => s.UserKey == userKey);

                if(data == null) return new MemberProfileT();

                return new MemberProfileT
                {
                    UserKey = data.UserKey,
                    UserId = data.Members.Id,
                    UserName = data.Members.Name,
                    NickName = data.NickName,
                    ProfileImageUrl = data.ProfileImageUrl,
                    ProfileImagePath = data.ProfileImagePath,
                    InsertDate = data.InsertDate,
                    InsertUserKey = data.InsertUserKey,
                    UpdateDate = data.UpdateDate,
                    UpdateUserKey = data.UpdateUserKey
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
    }
}
